package com.springboot.hikersystemapp.service.serviceImpl;

import com.springboot.hikersystemapp.domain.Team;
import com.springboot.hikersystemapp.domain.TeamMember;
import com.springboot.hikersystemapp.domain.User;

import com.springboot.hikersystemapp.repository.TeamMemberRepository;
import com.springboot.hikersystemapp.repository.TeamRepository;
import com.springboot.hikersystemapp.repository.UserRepository;

import com.springboot.hikersystemapp.service.ServiceInterface;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class servicempl implements ServiceInterface {
    @Resource
    private TeamMemberRepository teamMemberRepository;

    @Resource
    private TeamRepository teamRepository;

    @Resource
    private UserRepository userRepository;

    @Override
    public User registService(User user) {
        //当新用户的用户名已存在时
        if(userRepository.findByUsernameOrEmail(user.getUsername(), user.getEmail())!=null){
            // 无法注册
            return null;
        }
        else
        {
            //返回创建好的用户对象(带id)
            return user;
        }
    }

    @Override
    public User loginService(User userp) {
        // 如果账号密码都对则返回登录的用户对象，若有一个错误则返回null
        User user = userRepository.findByUsernameAndPassword(userp.getUsername(), userp.getPassword());
        // 重要信息置空
        if(user != null){
            user.setPassword("");
        }
        return user;
    }

    @Override
    public boolean changePassword(Long userId, String oldPassword, String newPassword) {
        User user = userRepository.findById(userId).orElse(null);
        if (user == null || !user.getPassword().equals(oldPassword)) {
            return false;
        }
        user.setPassword(newPassword);
        userRepository.save(user);
        return true;
    }

    @Override
    public boolean changeUsername(Long userId, String newUsername) {
        User user = userRepository.findById(userId).orElse(null);
        if (user == null) {
            return false;
        }
        user.setUsername(newUsername);
        userRepository.save(user);
        return true;
    }

    @Override
    public List<User> getUserList(  ) {
        List<User> userList = userRepository.findAll();
        return userList;
    }

    @Override
    public Team createTeam(User user, Team team) {
        String teamName = team.getName();
        List<Team> temp = teamRepository.findByName(teamName);
        if(temp.size() != 0){
            return null;
        }else{
            team.setAdmin(user);
            team.setStatus("joinable");
            teamRepository.save(team);

            return team;
        }
    }

    @Override
    public List<Team> getJoinableTeams(User user) {
        List<Team> joinableTeams = teamRepository.findByStatus("joinable");
        List<Team> jjteam = new ArrayList<>();

        for (Team team : joinableTeams){
            TeamMember teamMember =teamMemberRepository.findByTeamIdAndUserId(team.getId(), user.getId());
            if(!teamMember.getStatus().equals("approval")){
                jjteam.add(team);
            }
        }
        return jjteam;
    }

    @Override
    public void setTeamMember(User user, Team team) {
        TeamMember teamMember = teamMemberRepository.findByTeamIdAndUserId(team.getId(),user.getId());
        if (teamMember == null) {
            return ;
        }else{
            teamMember.setStatus("pending");
            teamMemberRepository.save(teamMember);
        }
    }

    @Override
    public List<TeamMember> getApplicationList(User user) {//查找自己为管理员的Team的一些TeamMembers
        List<Team> teams= teamRepository.findByAdmin_Id(user.getId());
        List<TeamMember> ApplicationList = new ArrayList<>();
        for(Team team:teams){
            List<TeamMember> teamMembers = teamMemberRepository.findByTeamId(team.getId());
            for(TeamMember teamMember : teamMembers) {
                if (teamMember.getStatus().equals("pending")) {
                    ApplicationList.add(teamMember);
                }
            }
            teamMembers.clear();
        }
        return ApplicationList;
    }

    @Override
    public TeamMember approveTeamMember(User user,TeamMember teamMember) {//管理员审核某个teamMember
        List<TeamMember> approveTeamMembers = getApplicationList(user);
        boolean flag = false;
        for (TeamMember m : approveTeamMembers) {
            if (m.getId().equals(teamMember.getId())) {
                flag=true;
            }
        }
        if(flag){//待审核成员在管理员的Team的一些TeamMembers中
            teamMember.setStatus("approval");
            teamMemberRepository.save(teamMember);
            Team team = teamMember.getTeam();
            int curMaxMembers=team.getMax_members();
            team.setMax_members(curMaxMembers-1);
            if(team.getMax_members()==0){
                team.setStatus("full");
            }
            teamRepository.save(team);
            return teamMember;
        }else{
            return null;
        }
    }

    // 根据当前 users 和 teams 表中的数据生成 team_members 表中的记录
    public void generateTeamMembers() {
        List<User> users = userRepository.findAll();
        List<Team> teams = teamRepository.findAll();
        for (User user : users) {
            for (Team team : teams) {
                // 检查是否已经存在相同的 User 和 Team 的记录
                TeamMember existingTeamMember = teamMemberRepository.findByTeamIdAndUserId(team.getId(), user.getId());

                if (existingTeamMember == null) {
                    // 如果不存在则创建新的 TeamMember 记录
                    TeamMember teamMember = new TeamMember();
                    teamMember.setUser(user);
                    teamMember.setTeam(team);
                    teamMember.setStatus("Null");
                    teamMemberRepository.save(teamMember);
                }
                // 如果已经存在，不改变 Status 属性
            }
        }
    }
}
